package com.shanghaionstar.home.presenter;

import android.content.Context;
import android.text.TextUtils;

import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.ExceptionUtil;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.sqlite.entities.OvdHistory;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.mag.enumtype.VehicleDigontiscResult;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.onstar.cn.vehicle.entity.RequestStatus;
import com.onstar.cn.vehicle.result.PollingResult;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.home.iview.IHomeView;
import com.shanghaionstar.home.model.DataRefreshParser;
import com.shanghaionstar.home.model.DrivingScore;
import com.shanghaionstar.home.model.HomeModel;
import com.shanghaionstar.sqlite.DataRefreshDBService;
import com.shanghaionstar.service.DataRefreshService;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.DateFormatUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConstants;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by 6335yz on 2016/7/5.
 */
public class DataRefreshPresenter extends BasePresenter {

    private DataRefreshService dataRefreshService;
    private Context context;
    private IHomeView homeView;
    private Subscription pollingSubscription, scoreSubscription;
    private DataRefreshDBService dataRefreshDBService;
    private BaseActivity baseActivity;

    public DataRefreshPresenter(IMVPScheduler mvpScheduler, Context context) {
        super(mvpScheduler);
        dataRefreshService = new DataRefreshService(context);
        dataRefreshDBService = new DataRefreshDBService(context);
        this.context = context;
        this.baseActivity = (BaseActivity) context;
        super.setServiceProvider(dataRefreshService);

        registPollingSub();
    }

    @Override
    public void setView(IMVPView view) {
        super.setView(view);
        homeView = (IHomeView) view;
    }

    /**
     * datarefresh 入口方法
     *
     * @param
     */
    public void doDataRefresh() {
        if (validateDataRefresh()) {
            subscription = dataRefreshService.doDataRefresh()
                    .subscribeOn(mvpScheduler.backgroundThread())
                    .observeOn(mvpScheduler.mainThread())
                    .subscribe(new Action1<String>() {
                        @Override
                        public void call(String s) {

                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            //里面抛出的Error信息
                            if (homeView != null) {
                                ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(baseActivity, new HttpException("", throwable.getMessage()));
                                homeView.onResponseError(new OnStarException("", errorInfo.getMsg()));
                            }

                        }
                    });
        }
    }

    public boolean validateDataRefresh() {
        if (BusinessUtil.checkInProgressCommand(context, null, true)) {
            if (homeView != null) {
                homeView.showCommandInProgress();
            }
            return false;
        }
        if (!BusinessUtil.checkDataRefreshAuth(baseActivity, Constants.ENTITLEMENT_M01DATA_REFRESH)) {
            homeView.onResponseError(null);
            return false;
        }
        return true;
    }
//
//    private ReportReqParam getRefreshReqParam(boolean isSuccess, String error) {
//        return new ReportReqParam.ReportReqParamBuilder().channelId("0")
//                .deviceType("0")
//                .functionNameFindId(FunctionNameFindId.CKSX.getStringValue())
//                .objectID("")
//                .objectType("9")
//                .operationType("")
//                .result(isSuccess ? "0" : "1")
//                .error(error)
//                .type("3").createReportReqParam();
//    }
//
//    private ReportReqParam getRefreshReqParam(boolean isSuccess) {
//        return getRefreshReqParam(isSuccess, "");
//    }

    /**
     * 处理Polling 返回结果
     */
    private void registPollingSub() {
        pollingSubscription = RxBus.getDefault()
                .toObserverable(RxConstants.ALL_PAGE_ALERT, PollingResult.class)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).filter(new Func1<PollingResult, Boolean>() {
                    @Override
                    public Boolean call(PollingResult pollingResult) {
                        return RemoteCommandsType.COMMANDS_DIAGNOSTICS.value().equals(pollingResult.getRequestType());
                    }
                })
                .subscribe(new Action1<PollingResult>() {
                    @Override
                    public void call(PollingResult pollingResult) {
                        LogManager.getInstance().d("datarefresh result--->>" + pollingResult.getJson());
                        if (RequestStatus.Success.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
                            updateResultToDB(pollingResult.getJson(), pollingResult.getCompleteTime());
                            BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.Home_DragDownRefresh.getStringValue(), ReportReqParam.getVehcileDataRefreshReqParam(FunctionNameFindId.Home_DragDownRefresh, true));
                            if (homeView != null) {
                                HomeModel homeModel = new DataRefreshParser().dataRefreshHomeModel(pollingResult.getJson(), DateFormatUtil.format3(context, pollingResult.getCompleteTime(), 8));
                                homeView.onReponseSuccess(loadRateStatus(homeModel));
                            }
                        } else if (RequestStatus.Failure.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
                            /**
                             * 刷新车况返回统一的错误?
                             */
                            BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.Home_DragDownRefresh.getStringValue(), ReportReqParam.getVehcileDataRefreshReqParam(FunctionNameFindId.Home_DragDownRefresh, false, pollingResult.getErrorInfo() == null ? "" : pollingResult.getErrorInfo().getMsg()));
                            if (homeView != null) {
                                homeView.onResponseError(new OnStarException("", context.getString(R.string.get_condition_error)));
                            }
                        } else {
                            //默认
                            if (homeView != null) {
                                BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.Home_DragDownRefresh.getStringValue(), ReportReqParam.getVehcileDataRefreshReqParam(FunctionNameFindId.Home_DragDownRefresh, false, pollingResult.getErrorInfo() == null ? "" : pollingResult.getErrorInfo().getMsg()));
                                homeView.onResponseError(new OnStarException("", context.getString(R.string.get_condition_error)));
                            }
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        homeView.onResponseError(new OnStarException("", context.getString(R.string.get_condition_error)));
                    }
                });
    }

    private void updateResultToDB(String json, String completionTime) {
        OvdHistory ovdhistory = new OvdHistory();
        ovdhistory.setVin(ApplicationUtil.getInstance().getVin());
        ovdhistory.setCreateDate(completionTime);
        ovdhistory.setContent(json);
        boolean isExits = dataRefreshDBService.checkDataIfExits(ApplicationUtil.getInstance().getVin());
        if (!isExits) {
            dataRefreshDBService.insert(ovdhistory); // 插入到本地数据
        } else {
            dataRefreshDBService.update(ovdhistory); // 更新本地数据
        }
    }


    private boolean isTireLegal(String value) {
        if (TextUtils.isEmpty(value))
            return false;
        return CommonUtil.isNumber(value) && Integer.parseInt(value) >= 0;
    }

    private boolean isAllTireLegal(HomeModel homeModel) {
        return isTireLegal(homeModel.tv_front_left_value) &&
                isTireLegal(homeModel.tv_front_right_value) &&
                isTireLegal(homeModel.tv_rear_left_value) &&
                isTireLegal(homeModel.tv_rear_right_value);
    }

    /**
     * 根据车辆状态规则生成所需的展示类
     */
    private HomeModel loadRateStatus(HomeModel homeModel) {
        if (homeModel == null) return null;
        List<String> tireList = new ArrayList<String>();
        List<String> statusList = new ArrayList<String>();

        // 胎压
        if (isAllTireLegal(homeModel) && ApplicationUtil.getInstance().getSupportedDiagnostic( Constants.TIRE_PRESSURE)) {
            if (!CommonUtil.isNull(homeModel.leftFront) && !CommonUtil.isNull(homeModel.leftRear) && !CommonUtil.isNull(homeModel.rightFront)
                    && !CommonUtil.isNull(homeModel.rightRear)) {
                tireList.add(homeModel.leftFront.toLowerCase(Locale.CHINA));
                tireList.add(homeModel.leftRear.toLowerCase(Locale.CHINA));
                tireList.add(homeModel.rightFront.toLowerCase(Locale.CHINA));
                tireList.add(homeModel.rightRear.toLowerCase(Locale.CHINA));
                if (!tireList.contains("yellow") && !tireList.contains("red")) {
                    statusList.add("green");
                } else if (tireList.contains("red")) {
                    statusList.add("red");
                } else {
                    statusList.add("yellow");
                }
            }
        }
        // 机油
        if (ApplicationUtil.getInstance().getSupportedDiagnostic( Constants.OIL_LIFE)) {
//        if (homeModel.oilLife != -1) {//-1代表该车不支持机油检查
            if (homeModel.oilLife > 20 && homeModel.oilLife <= 100) {
                statusList.add("green");
            } else if (homeModel.oilLife > 0 && homeModel.oilLife <= 20) {
                statusList.add("yellow");
            } else {
                statusList.add("red");
            }
        }
        // 燃油
        if (homeModel.fuelTankInfo > 92 && homeModel.fuelTankInfo <= 100) {
            statusList.add("green");
        } else if (homeModel.fuelTankInfo > 30 && homeModel.fuelTankInfo <= 92) {
            statusList.add("green");
        } else if (homeModel.fuelTankInfo > 8 && homeModel.fuelTankInfo <= 30) {
            statusList.add("yellow");
        } else {
            statusList.add("red");
        }
        //电量
        if (ApplicationUtil.getInstance().isPhev()) {
            if (CommonUtil.isNumerice(homeModel.batteryLevel)) {
                float iBatteryLevel = Float.valueOf(homeModel.batteryLevel);
                if (iBatteryLevel > 20 && iBatteryLevel <= 100) {
                    statusList.add("green");
                } else if (iBatteryLevel > 0 && iBatteryLevel <= 20) {
                    statusList.add("yellow");
                } else {
                    statusList.add("red");
                }
            }
        }

        if (!statusList.contains("yellow") && !statusList.contains("red")) {//车况正常（正常就是最好的情况即绿色）
            homeModel.statusRate = context.getString(R.string.dignotics_status_excellent);
            homeModel.statusRateDesc = context.getString(R.string.dignotics_status_excellent_msg);
            homeModel.ball_img_res = getBallImgRes(VehicleDigontiscResult.GOOD);
        } else if (statusList.contains("red")) {
            homeModel.statusRate = context.getString(R.string.dignotics_status_poor);
            homeModel.statusRateDesc = context.getString(R.string.dignotics_status_poor_msg);
            homeModel.ball_img_res = getBallImgRes(VehicleDigontiscResult.BAD);
        } else {//车况良好（比正常稍差的情况）
            homeModel.statusRate = context.getString(R.string.dignotics_status_good);
            homeModel.statusRateDesc = context.getString(R.string.dignotics_status_good_msg);
            homeModel.ball_img_res = getBallImgRes(VehicleDigontiscResult.NORMAL);
        }
        //test value animation
//        homeModel.fuel_value = 70f;
        homeModel.fuelDegree = getDegreeByValue(homeModel.fuel_value);
        return homeModel;
    }

    /**
     * @param vehicleDigontiscResult
     * @return 得到中间大球的样式
     */
    private int getBallImgRes(VehicleDigontiscResult vehicleDigontiscResult) {
        int res;
        if (vehicleDigontiscResult == null) return 0;
        switch (vehicleDigontiscResult) {
            case GOOD:
                res = R.drawable.status_good;
                break;
            case NORMAL:
                res = R.drawable.status_normal;
                break;
            case BAD:
                res = R.drawable.status_bad;
                break;
            default:
                res = 0;
                break;
        }
        return res;
    }

    public void unRegisterSubscriber() {
        if (pollingSubscription != null && !pollingSubscription.isUnsubscribed()) {
            pollingSubscription.unsubscribe();
        }
        if (scoreSubscription != null && !scoreSubscription.isUnsubscribed()) {
            scoreSubscription.unsubscribe();
        }
    }

    /**
     * @return void 返回类型
     * @throws
     * @Title: getHistoryOVD
     * @Description: 获取历史OVD数据
     */
    public void getHistoryOVD() {
        try {
            OvdHistory ovdhistory = dataRefreshDBService.getOvdHistory(ApplicationUtil.getInstance().getVin());
            if (ovdhistory == null) {
                if (homeView != null) {
                    homeView.onLoadDataRefresh();
                }
            } else {
                //设置开则刷新，关则不刷新
                if (PreferencesUtls.getInstance(baseActivity).getBoolean(FinalConstants.SharedPreferencesConfig.OVD_AUTO_REFRESH, false)) {
                    if (homeView != null) {
                        homeView.onLoadDataRefresh();
                    }
                } else {
                    if (homeView != null) {
                        HomeModel homeModel = new DataRefreshParser().dataRefreshHomeModel(ovdhistory.getContent(), DateFormatUtil.format3(context, ovdhistory.getCreateDate(), 8));
                        homeView.onReponseSuccess(loadRateStatus(homeModel));
                    }
                }
            }

        } catch (final Exception e) {
            homeView.onResponseError(new OnStarException("", ExceptionUtil.defaultException(e)));
        }
    }

    private static final float START_DEGREE = 0f;
    private static final float END_DEGREE = 180f;

    private float getDegreeByValue(float value) {
        //起始度数73.2f,结束度数96f; 每升汽油代表(73.2+96)/100;
        if (value < 0) {
            value = 0;
        }
        if (value > 100) {
            value = 100;
        }
        float degree = value * (END_DEGREE - START_DEGREE) / 100f;
        return (START_DEGREE + degree);
    }

    public void loadDrivingScore() {
        scoreSubscription = dataRefreshService.loadDrivingScore()
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<DrivingScore>() {
                    @Override
                    public void call(DrivingScore drivingScore) {
                        homeView.showDrivingScore(drivingScore);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        if (throwable != null && throwable instanceof OnStarException)
                            homeView.showLoadDrivingScoreErr(throwable);
                    }
                });
    }
}
